<template>
  <el-drawer :model-value="true" size="480px" :with-header="false" @close="$emit('close')">
    <div class="task-detail-wrapper">
      <div class="task-detail-title">任务详情</div>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="task">
        <el-form label-width="80px" class="task-detail-form" ref="formRef">
          <el-form-item label="任务标题">
            <el-input v-model="task.title" />
          </el-form-item>
          <el-form-item label="优先级">
            <el-radio-group v-model="task.priority">
              <el-radio-button label="H">高</el-radio-button>
              <el-radio-button label="M">中</el-radio-button>
              <el-radio-button label="L">低</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="截止日期">
            <el-date-picker v-model="task.due_date" type="date" />
          </el-form-item>
          <el-form-item label="标签">
            <el-select v-model="task.tagIds" multiple filterable placeholder="请选择标签" style="width: 100%">
              <el-option v-for="tag in allTags" :key="tag.id" :label="tag.name" :value="tag.id">
                <el-tag :style="{ backgroundColor: tag.color + '22', color: tag.color, border: 'none', marginRight: '6px' }">{{ tag.name }}</el-tag>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="task.categoryId" filterable placeholder="请选择分类" style="width: 100%">
              <el-option v-for="cat in allCategories" :key="cat.id" :label="cat.name" :value="cat.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务描述">
            <el-input type="textarea" v-model="task.description" :rows="4" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="error">未找到任务信息</div>
      <div class="task-detail-footer">
        <el-button type="primary" @click="onSave" :loading="saving">保存更改</el-button>
        <el-button @click="$emit('close')" type="danger">关闭</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import http from '../utils/http'

const props = defineProps({
  taskId: {
    type: [Number, String],
    required: false
  }
})
const emit = defineEmits(['close', 'saved'])
const task = ref(null)
const loading = ref(false)
const saving = ref(false)
const allTags = ref([])
const allCategories = ref([])
const formRef = ref()

async function fetchTaskDetail(id) {
  if (id === null || id === undefined) {
    // 新建任务，初始化空表单
    task.value = {
      title: '',
      priority: 'M',
      due_date: '',
      description: '',
      tagIds: [],
      categoryId: null
    }
    return
  }
  loading.value = true
  try {
    const res = await http(`/api/tasks/${id}`)
    if (!res.ok) throw new Error('请求失败')
    const data = await res.json()
    task.value = {
      ...data,
      tagIds: data.tags.map(t => t.id),
      categoryId: data.category?.id || null
    }
  } catch (e) {
    ElMessage.error('获取任务详情失败')
    task.value = null
  } finally {
    loading.value = false
  }
}

async function fetchTags() {
  try {
    const res = await http('/api/tags')
    const data = await res.json()
    allTags.value = data.results
  } catch {}
}
async function fetchCategories() {
  try {
    const res = await http('/api/categories')
    const data = await res.json()
    allCategories.value = data.results
  } catch {}
}

async function onSave() {
  if (!task.value) return
  saving.value = true
  try {
    const payload = {
      title: task.value.title,
      priority: task.value.priority,
      due_date: task.value.due_date,
      description: task.value.description,
      tag_ids: task.value.tagIds,
      category_id: task.value.categoryId
    }
    
    let res
    if (props.taskId) {
      res = await http(`/api/tasks/${props.taskId}`, {
        method: 'PUT',
        body: JSON.stringify(payload)
      })
    } else {
      res = await http('/api/tasks', {
        method: 'POST',
        body: JSON.stringify(payload)
      })
    }
    if (!res.ok) throw new Error('保存失败')
    ElMessage.success('保存成功')
    emit('saved')
  } catch {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

watch(() => props.taskId, (id) => {
  fetchTaskDetail(id)
}, { immediate: true })

fetchTags()
fetchCategories()
</script>

<style scoped>
.task-detail-wrapper {
  padding: 24px 18px 0 18px;
}
.task-detail-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 18px;
}
.task-detail-form {
  margin-bottom: 18px;
}
.task-detail-footer {
  text-align: right;
  margin-top: 18px;
}
.loading {
  color: #888;
  text-align: center;
  margin: 32px 0;
}
.error {
  color: #f56c6c;
  text-align: center;
  margin: 32px 0;
}
</style> 